Let's say I have an ArrayList of objects. For example: ArrayList<Person> personList, where each Person has 2 class variables String name and int age. These variables each have their own getter methods getName() and getAge().
What is the simplest way to retrieve an array (or ArrayList) of int ages[]?
Note this question is similar to the verbosely titled "Retrieve an array of values assigned to a particular class member from an array of objects in java", though without the arbitrary restriction on for-loops, and using an ArrayList instead of an Array.
Create a target array of the same size as the list then iterate through the list and add each element's age to the target array.
Numerous ways to do this -- here is one.
First get the ages into a list (using a java8 stream), and then convert the list into an array.
public int[] getAges() {
return personList.stream()
.mapToInt(Person::getAge)
.toArray();
}
Person P1 = new Person("Dev", 25);
Person P2 = new Person("Andy", 12);
Person P3 = new Person("Mark", 20);
Person P4 = new Person("Jon", 33);
ArrayList<Person> personList = new ArrayList<>(Arrays.asList(new Person[] { P1, P2, P3, P4 }));
int[] ages = getPersonAges(personList); // [25, 12, 20, 33]
private static int[] getPersonAges(ArrayList<Person> personList) {
int[] ages = new int[personList.size()];
int idx = 0;
for (Person P : personList) { // Iterate through the personList
int age = P.getAge();
ages[idx++] = age;
}
return ages;
}